# -*- coding: utf-8 -*-
'''
Created on 09/nov/2009

@author: sax
'''
from django import forms, template
from xadmin import helpers, widgets
from xadmin.util import unquote, flatten_fieldsets, get_deleted_objects, model_ngettext, model_format_dict
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.db import models, transaction
from django.db.models.fields import BLANK_CHOICE_DASH
from django.forms.formsets import all_valid
from django.forms.models import BaseInlineFormSet, modelform_factory, modelformset_factory, inlineformset_factory
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.utils.datastructures import SortedDict
from django.utils.encoding import force_unicode
from django.utils.functional import curry, update_wrapper
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext as _, ungettext, ugettext_lazy
from xadmin.ajax.service import AjaxService

import logging
LOGGER = logging.getLogger('xadmin.xamodeladmin')

from xadmin.options.strategies import Strategy

class ServicesStrategy(Strategy):
        
    
    def __set__(self, owner, value):  
        super(ServicesStrategy, self).__set__(owner, value)
        self.owner = owner
        
        self.owner.fk_service = None
        self.owner.fk_service_viewname = None           
        self.owner._services = self._services = {}
        self.model = owner.model
        #self.setup_service_for_foreign_key()
    
    
    def setup_service_for_foreign_key(self):        
        self.owner.fk_service_viewname = '%s_%s_service_fk' % (self.model._meta.app_label, self.model._meta.module_name)
        if self.fk_service is None:
            return
        LOGGER.debug(self.model)
        if isinstance(self.fk_service, AjaxService):
            self._services['fk'] = (self.fk_service_viewname, self.fk_service)

        elif isinstance(self.fk_service, (list, tuple)) and isinstance(self.fk_service[0], (list, tuple)):
            self.fk_service[0].insert(0, 'pk')
            self._services['fk'] = (self.fk_service_viewname,
                                     AjaxService(self.model.objects.all(), self.fk_service[0], self.fk_service[1])
                                     )

        elif bool(self.fk_service):
            ret_fields = ['pk']
            criteria = []
            for f in self.fk_service:
                ret_fields.append(f)
                criteria.append('%s__istartswith' % f)
            self._services['fk'] = (self.fk_service_viewname,
                                     AjaxService(self.model.objects.all(), ret_fields, criteria)
                                     )
    def extra_urls(self, urlpatterns):
        from django.conf.urls.defaults import patterns, url
        ret = []
        
        for fieldname, service in self._services.items():
            uri = r'^service/%s/$' % fieldname
            LOGGER.info("created service %s for %s on %s" % (uri, service[1], self.model))
            ret.append(url(uri,
                                self._wrap_view(service[1]),
                                name=service[0]
                                ),
                        )
        
        return patterns('', *ret) + urlpatterns     
        
